const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const { exec } = require('child_process');
const { promisify } = require('util');
const archiver = require('archiver');
const nodeManager = require('../utils/nodeManager');
const dockerBuildManager = require('../utils/dockerBuildManager');
const skipBuildManager = require('../utils/skipBuildManager');
const logManager = require('../utils/logManager');
const retryManager = require('../utils/retryManager');
const packageIndexManager = require('../utils/packageIndexManager');
const windowsBuildManager = require('../utils/windowsBuildManager');

const router = express.Router();
const execAsync = promisify(exec);

/**
 * 获取环境域名配置
 * GET /api/build/environments
 */
router.get('/environments', async (req, res) => {
  try {
    const environments = {
      test: Array.from({length: 40}, (_, i) => ({
        key: `test${String(i + 1).padStart(2, '0')}`,
        name: `测试环境${String(i + 1).padStart(2, '0')}`,
        url: `https://test${String(i + 1).padStart(2, '0')}.xnzn.net`,
        type: 'test'
      })),
      dev: Array.from({length: 40}, (_, i) => ({
        key: `dev${String(i + 1).padStart(2, '0')}`,
        name: `开发环境${String(i + 1).padStart(2, '0')}`,
        url: `https://dev${String(i + 1).padStart(2, '0')}.xnzn.net`,
        type: 'dev'
      }))
    };

    res.json({
      success: true,
      environments,
      default: 'test01'
    });
  } catch (error) {
    res.status(500).json({ 
      error: '获取环境配置失败', 
      message: error.message 
    });
  }
});

/**
 * Windows环境诊断
 * GET /api/build/windows-diagnosis
 */
router.get('/windows-diagnosis', async (req, res) => {
  try {
    const diagnosis = await windowsBuildManager.diagnoseAndSuggest();
    
    if (!diagnosis.applicable) {
      return res.json({
        success: true,
        applicable: false,
        message: '当前不是Windows环境'
      });
    }

    res.json({
      success: true,
      applicable: true,
      platform: process.platform,
      status: diagnosis.status,
      suggestions: diagnosis.suggestions
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * 获取包索引信息
 * GET /api/build/package-indexes
 */
router.get('/package-indexes', async (req, res) => {
  try {
    const indexes = await packageIndexManager.getAllIndexes();
    res.json({
      success: true,
      indexes
    });
  } catch (error) {
    res.status(500).json({ 
      error: '获取包索引失败', 
      message: error.message 
    });
  }
});

/**
 * 重置平台包索引
 * POST /api/build/reset-index/:platform
 */
router.post('/reset-index/:platform', async (req, res) => {
  try {
    const { platform } = req.params;
    await packageIndexManager.resetPlatformIndex(platform);
    res.json({
      success: true,
      message: `${platform} 平台索引已重置`
    });
  } catch (error) {
    res.status(500).json({ 
      error: '重置索引失败', 
      message: error.message 
    });
  }
});

/**
 * 获取可用的构建策略
 * GET /api/build/strategies
 */
router.get('/strategies', async (req, res) => {
  try {
    const dockerAvailable = await dockerBuildManager.checkDockerAvailable();
    
    const strategies = [
      {
        key: 'auto',
        name: '智能模式',
        description: '自动选择最佳构建策略',
        recommended: true,
        available: true
      },
      {
        key: 'skip',
        name: '跳过模式', 
        description: '跳过问题依赖，快速构建',
        recommended: false,
        available: true
      },
      {
        key: 'docker',
        name: 'Docker模式',
        description: '真正的Node版本隔离 (推荐)',
        recommended: dockerAvailable,
        available: dockerAvailable
      },
      {
        key: 'traditional',
        name: '传统模式',
        description: '使用当前Node环境',
        recommended: false,
        available: true
      }
    ];

    res.json({
      success: true,
      strategies,
      dockerAvailable
    });
  } catch (error) {
    console.error('获取构建策略失败:', error);
    res.status(500).json({ error: '获取构建策略失败' });
  }
});

/**
 * 获取支持的Node.js版本列表
 * GET /api/build/node-versions
 */
router.get('/node-versions', async (req, res) => {
  try {
    const versions = nodeManager.getSupportedVersions();
    res.json({
      success: true,
      versions
    });
  } catch (error) {
    console.error('获取Node版本失败:', error);
    res.status(500).json({ error: '获取Node版本失败' });
  }
});

/**
 * 检测项目推荐的Node版本
 * POST /api/build/detect-node-version
 */
router.post('/detect-node-version', async (req, res) => {
  try {
    const { projectId } = req.body;
    
    if (!projectId) {
      return res.status(400).json({ error: '项目ID不能为空' });
    }

    const projectPath = path.join(__dirname, '../../temp', projectId);
    
    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const recommendedVersion = await nodeManager.detectRecommendedVersion(projectPath);
    const versionInfo = nodeManager.supportedVersions[recommendedVersion];

    res.json({
      success: true,
      recommended: recommendedVersion,
      versionInfo,
      reason: getVersionReason(projectPath, recommendedVersion)
    });

  } catch (error) {
    console.error('检测Node版本失败:', error);
    res.status(500).json({ error: '检测Node版本失败' });
  }
});

/**
 * 获取版本推荐原因
 */
async function getVersionReason(projectPath, version) {
  try {
    const packagePath = path.join(projectPath, 'package.json');
    if (!await fs.pathExists(packagePath)) {
      return '默认推荐稳定版本';
    }

    const pkg = await fs.readJson(packagePath);
    const deps = { ...pkg.dependencies, ...pkg.devDependencies };

    if (deps['node-sass']) return '项目使用node-sass，推荐Node 14以避免编译问题';
    if (deps['@vue/cli-service']) return '检测到Vue CLI项目，推荐稳定版本';
    if (deps['next']) return '检测到Next.js项目';
    if (deps['vite']) return '检测到Vite项目，推荐Node 16+';

    return '根据项目依赖分析推荐';
  } catch (error) {
    return '自动检测推荐';
  }
}

/**
 * 开始构建项目
 * POST /api/build/start
 */
router.post('/start', async (req, res) => {
  const { projectId, envVars = {}, buildOptions = {} } = req.body;
  
  if (!projectId) {
    return res.status(400).json({ error: '项目ID不能为空' });
  }

  const projectPath = path.join(__dirname, '../../temp', projectId);
  
  if (!await fs.pathExists(projectPath)) {
    return res.status(404).json({ error: '项目不存在' });
  }

  // 设置Node版本、构建策略和平台
  const nodeVersion = buildOptions.nodeVersion || 'node14';
  const buildStrategy = buildOptions.strategy || 'auto'; // auto, docker, skip
  const platform = buildOptions.platform || 'h5'; // 构建平台
  const maxRetries = buildOptions.maxRetries || 3; // 最大重试次数
  const environment = buildOptions.environment || 'test01'; // 环境域名配置
  const apiUrl = buildOptions.apiUrl; // 自定义API地址，优先级最高
  
  // 获取最终的API URL
  let finalApiUrl = apiUrl;
  if (!finalApiUrl) {
    // 根据环境配置生成API URL
    finalApiUrl = `https://${environment}.xnzn.net`;
  }

  // 保存构建配置信息（包含域名）到项目目录
  const buildConfigPath = path.join(projectPath, '.build-config.json');
  await fs.writeJson(buildConfigPath, {
    projectId,
    nodeVersion,
    buildStrategy,
    platform,
    environment,
    apiUrl: finalApiUrl,
    maxRetries,
    buildTime: new Date().toISOString()
  }, { spaces: 2 });

  // 发送构建开始日志
  logManager.sendBuildStart(projectId, {
    nodeVersion,
    buildStrategy,
    platform,
    envVars,
    maxRetries,
    environment,
    apiUrl: finalApiUrl
  });

  logManager.sendBuildStep(projectId, '配置', `Node ${nodeVersion}, 策略: ${buildStrategy}, 平台: ${platform}, 环境: ${environment}, API: ${finalApiUrl}, 最大重试: ${maxRetries}次`);
  
  try {
    // 使用重试机制执行构建
    const { buildResult, downloadInfo } = await retryManager.executeWithRetry(
      projectId,
      async (attempt) => {
        logManager.sendLog(projectId, {
          level: 'info',
          message: `🔨 开始第${attempt}次构建尝试`,
          data: { attempt, maxRetries }
        });

        // 清理历史构建产物，确保全新构建
        await cleanPreviousBuild(projectPath, projectId);

        let buildResult;
        
        // 扩展构建选项，包含API URL信息
        const extendedBuildOptions = {
          ...buildOptions,
          apiUrl: finalApiUrl,
          environment,
          platform
        };

        // Windows环境智能策略选择
        if (process.platform === 'win32') {
          const windowsStrategy = await windowsBuildManager.selectBuildStrategy(projectPath, nodeVersion, extendedBuildOptions);
          logManager.sendBuildStep(projectId, 'Windows策略', `选择构建策略: ${windowsStrategy.strategy} (${windowsStrategy.reason})`);
          
          if (windowsStrategy.strategy === 'error') {
            throw new Error(`Windows环境配置问题: ${windowsStrategy.issues.join(', ')}\n建议: ${windowsStrategy.suggestions.join('; ')}`);
          }
        }

        // 根据策略选择构建方法
        if (buildStrategy === 'docker' && await dockerBuildManager.checkDockerAvailable()) {
          logManager.sendDockerLog(projectId, '使用Docker容器构建 (真正的Node版本隔离)');
          buildResult = await dockerBuildManager.buildWithDocker(projectPath, nodeVersion, envVars, platform, projectId, finalApiUrl);
          
        } else if (buildStrategy === 'skip' || buildStrategy === 'auto') {
          // Windows环境下，如果Docker不可用，尝试本地构建
          if (process.platform === 'win32' && !(await dockerBuildManager.checkDockerAvailable())) {
            logManager.sendBuildStep(projectId, '策略', 'Windows环境Docker不可用，使用本地构建');
            buildResult = await windowsBuildManager.buildWithLocalWindows(projectPath, nodeVersion, envVars, platform, projectId, finalApiUrl);
          } else {
            logManager.sendBuildStep(projectId, '策略', '使用跳过策略构建 (忽略问题依赖)');
            buildResult = await skipBuildManager.buildProject(projectPath, nodeVersion, envVars, extendedBuildOptions, projectId);
          }
          
        } else {
          logManager.sendBuildStep(projectId, '策略', '使用传统构建方法');
          // 传统方法 (可能遇到Node版本问题)
          try {
            await nodeManager.setupNodeVersion(projectPath, nodeVersion);
          } catch (setupError) {
            logManager.sendLog(projectId, {
              level: 'warning',
              message: `Node版本设置失败，使用当前环境: ${setupError.message}`
            });
          }

          await injectEnvironmentVariables(projectPath, envVars);
          await installDependencies(projectPath, nodeVersion, projectId);
          buildResult = await buildProject(projectPath, extendedBuildOptions, nodeVersion, projectId);
        }
        
        // 打包构建产物
        logManager.sendPackageLog(projectId, '开始打包构建产物...');
        const downloadInfo = await packageBuildOutput(projectId, projectPath, buildResult.outputDir, platform);
        
        return { buildResult, downloadInfo };
      },
      {
        maxAttempts: maxRetries,
        retryDelay: 10000, // 10秒重试间隔
        retryableErrors: [
          'TIMEOUT',
          'NETWORK', 
          'DEPENDENCY_INSTALL',
          'BUILD_COMMAND',
          'DOCKER_BUILD'
        ]
      }
    );
    
    // 发送构建成功日志
    logManager.sendBuildSuccess(projectId, {
      buildResult,
      downloadInfo
    });
    
    res.json({
      success: true,
      message: '构建完成',
      buildResult,
      downloadInfo
    });

  } catch (error) {
    console.error('构建最终失败:', error);
    
    // 发送构建错误日志
    logManager.sendBuildError(projectId, error);
    
    res.status(500).json({ 
      error: '构建失败', 
      message: error.message,
      logs: error.logs || [],
      attempts: retryManager.getCurrentAttempt(projectId)
    });
  }
});

/**
 * 取消构建重试
 * POST /api/build/cancel-retry/:projectId
 */
router.post('/cancel-retry/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    
    if (retryManager.isRetrying(projectId)) {
      retryManager.cancelRetry(projectId);
      res.json({
        success: true,
        message: '重试已取消'
      });
    } else {
      res.json({
        success: false,
        message: '该项目当前没有进行重试'
      });
    }
  } catch (error) {
    res.status(500).json({ 
      error: '取消重试失败', 
      message: error.message 
    });
  }
});

/**
 * 获取构建状态（包括重试信息）
 * GET /api/build/status/:projectId
 */
router.get('/status/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    
    res.json({
      success: true,
      status: {
        isRetrying: retryManager.isRetrying(projectId),
        currentAttempt: retryManager.getCurrentAttempt(projectId),
        logs: logManager.getBuildLogs(projectId)
      }
    });
  } catch (error) {
    res.status(500).json({ 
      error: '获取状态失败', 
      message: error.message 
    });
  }
});

/**
 * 获取构建日志历史
 * GET /api/build/logs/:projectId
 */
router.get('/logs/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    const logs = logManager.getBuildLogs(projectId);
    
    res.json({
      success: true,
      logs
    });
  } catch (error) {
    console.error('获取构建日志失败:', error);
    res.status(500).json({ error: '获取构建日志失败' });
  }
});

/**
 * 清理构建日志
 * DELETE /api/build/logs/:projectId
 */
router.delete('/logs/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    logManager.clearBuildLogs(projectId);
    
    res.json({
      success: true,
      message: '日志已清理'
    });
  } catch (error) {
    console.error('清理构建日志失败:', error);
    res.status(500).json({ error: '清理构建日志失败' });
  }
});

/**
 * 获取项目可用的构建平台
 * GET /api/build/platforms/:projectId
 */
router.get('/platforms/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    const projectPath = path.join(__dirname, '../../temp', projectId);
    
    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const packagePath = path.join(projectPath, 'package.json');
    if (!await fs.pathExists(packagePath)) {
      return res.status(404).json({ error: 'package.json不存在' });
    }

    const pkg = await fs.readJson(packagePath);
    const scripts = pkg.scripts || {};
    
    // 检测uni-app项目
    const isUniApp = pkg.dependencies?.['@dcloudio/uni-app'] || 
                    pkg.devDependencies?.['@dcloudio/uni-app'] ||
                    pkg.dependencies?.['@dcloudio/vue-cli-plugin-uni'] ||
                    pkg.devDependencies?.['@dcloudio/vue-cli-plugin-uni'];

    const platforms = [];

    if (isUniApp) {
      // uni-app平台
      const uniPlatforms = [
        { key: 'h5', name: 'H5通用版', command: 'build:h5', description: '微信公众号、企业微信等H5应用' },
        { key: 'mp-weixin', name: '微信小程序', command: 'build:mp-weixin', description: '微信小程序平台' },
        { key: 'mp-alipay', name: '支付宝小程序', command: 'build:mp-alipay', description: '支付宝小程序平台' },
        { key: 'h5-scangzh', name: '微信公众号', command: 'build:custom h5-scangzh', description: '微信公众号应用' },
        { key: 'h5-qywx', name: '企业微信应用', command: 'build:custom h5-qywx', description: '企业微信应用' },
        { key: 'h5-alipaydd', name: '钉钉微应用', command: 'build:custom h5-alipaydd', description: '钉钉微应用' },
        { key: 'h5-nonghang-zj', name: '浙江农行应用', command: 'build:custom h5-nonghang-zj', description: '浙江农行应用' },
        { key: 'h5-nonghang-js', name: '江苏农行应用', command: 'build:custom h5-nonghang-js', description: '江苏农行应用' },
        { key: 'h5-nonghang-js-old', name: '江苏农行智慧政企版', command: 'build:custom h5-nonghang-js-old', description: '江苏农行智慧政企版本' },
        { key: 'h5-huanzhe', name: 'H5患者平台', command: 'build:custom h5-huanzhe', description: 'H5患者平台应用' },
        { key: 'weixin-huanzhe', name: '微信小程序患者平台', command: 'build:custom weixin-huanzhe', description: '微信小程序患者平台' },
        { key: 'alipay-huanzhe', name: '支付宝小程序患者平台', command: 'build:custom alipay-huanzhe', description: '支付宝小程序患者平台' }
      ];

      // 检查哪些平台有对应的构建脚本
      for (const platform of uniPlatforms) {
        // H5平台默认可用
        // 或者有对应的构建脚本
        // 或者是 build:custom / dev:custom 的自定义平台（检查是否有对应的基础命令）
        const isCustomPlatform = platform.command.includes('build:custom') || platform.command.includes('dev:custom');
        const hasCustomCommand = isCustomPlatform && (scripts['build:custom'] || scripts['dev:custom']);
        
        if (scripts[platform.command] || hasCustomCommand || isCustomPlatform) {
          platforms.push({
            ...platform,
            available: true
          });
        }
      }
    } else {
      // 普通项目
      if (scripts.build) {
        platforms.push({
          key: 'default',
          name: '默认构建',
          command: 'build',
          description: '标准构建命令',
          available: true
        });
      }
    }

    res.json({
      success: true,
      platforms,
      isUniApp
    });

  } catch (error) {
    console.error('获取构建平台失败:', error);
    res.status(500).json({ error: '获取构建平台失败' });
  }
});

/**
 * 获取构建状态
 * GET /api/build/status/:projectId
 */
router.get('/status/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    const projectPath = path.join(__dirname, '../../temp', projectId);
    
    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    // 检查构建状态（这里简化处理，实际项目中可使用Redis存储状态）
    const statusFile = path.join(projectPath, '.build-status.json');
    let status = { status: 'pending', progress: 0 };
    
    if (await fs.pathExists(statusFile)) {
      status = await fs.readJson(statusFile);
    }

    res.json({ success: true, ...status });

  } catch (error) {
    console.error('获取状态错误:', error);
    res.status(500).json({ error: '获取状态失败' });
  }
});

/**
 * 注入环境变量到项目
 */
async function injectEnvironmentVariables(projectPath, envVars) {
  try {
    // 生成.env文件
    const envContent = Object.entries(envVars)
      .map(([key, value]) => `${key}=${value}`)
      .join('\n');
    
    const envPath = path.join(projectPath, '.env');
    await fs.writeFile(envPath, envContent);
    
    console.log(`✅ 环境变量已注入: ${Object.keys(envVars).length}个变量`);
    
    // 如果项目没有dotenv依赖，动态添加
    const packagePath = path.join(projectPath, 'package.json');
    if (await fs.pathExists(packagePath)) {
      const pkg = await fs.readJson(packagePath);
      if (!pkg.dependencies?.dotenv && !pkg.devDependencies?.dotenv) {
        pkg.devDependencies = pkg.devDependencies || {};
        pkg.devDependencies.dotenv = '^16.3.1';
        await fs.writeJson(packagePath, pkg, { spaces: 2 });
        console.log('✅ 已添加dotenv依赖');
      }
    }

  } catch (error) {
    console.error('环境变量注入失败:', error);
    throw new Error(`环境变量注入失败: ${error.message}`);
  }
}

/**
 * 安装项目依赖（错误隔离版本）
 */
async function installDependencies(projectPath, nodeVersion = 'node14') {
  try {
    return await _performInstallDependencies(projectPath, nodeVersion);
  } catch (error) {
    // 错误隔离：包装并重新抛出
    const wrappedError = new Error(`依赖安装隔离错误: ${error.message}`);
    wrappedError.originalError = error;
    wrappedError.code = 'DEPENDENCY_INSTALL';
    throw wrappedError;
  }
}

/**
 * 内部依赖安装实现
 */
async function _performInstallDependencies(projectPath, nodeVersion = 'node14') {
  try {
    console.log('📦 开始安装依赖...');
    
    // 检查包管理器
    let packageManager = 'npm';
    if (await fs.pathExists(path.join(projectPath, 'yarn.lock'))) {
      packageManager = 'yarn';
    } else if (await fs.pathExists(path.join(projectPath, 'pnpm-lock.yaml'))) {
      packageManager = 'pnpm';
    }
    
    // 获取针对Node版本优化的安装命令
    let installCommand;
    if (packageManager === 'npm') {
      installCommand = nodeManager.getInstallCommand(nodeVersion);
    } else {
      installCommand = packageManager === 'yarn' ? 'yarn install' : 'pnpm install';
    }
    
    const { stdout, stderr } = await execAsync(installCommand, { 
      cwd: projectPath,
      timeout: 600000, // 10分钟超时（老版本Node安装较慢）
      env: { 
        ...process.env,
        NODE_OPTIONS: nodeVersion === 'node14' ? '--max-old-space-size=4096' : '',
        PYTHON: '/usr/bin/python3' // 设置Python路径以解决node-gyp问题
      }
    });
    
    console.log('✅ 依赖安装完成');
    return { stdout, stderr, packageManager };

  } catch (error) {
    console.error('依赖安装失败:', error);
    throw new Error(`依赖安装失败: ${error.message}`);
  }
}

/**
 * 构建项目（错误隔离版本）
 */
async function buildProject(projectPath, buildOptions = {}, nodeVersion = 'node14') {
  try {
    return await _performBuildProject(projectPath, buildOptions, nodeVersion);
  } catch (error) {
    // 错误隔离：包装并重新抛出
    const wrappedError = new Error(`项目构建隔离错误: ${error.message}`);
    wrappedError.originalError = error;
    wrappedError.code = 'BUILD_COMMAND';
    throw wrappedError;
  }
}

/**
 * 内部项目构建实现
 */
async function _performBuildProject(projectPath, buildOptions = {}, nodeVersion = 'node14') {
  try {
    console.log('🔨 开始构建项目...');
    
    // 读取package.json确定构建命令
    const packagePath = path.join(projectPath, 'package.json');
    let baseBuildCommand = 'npm run build';
    
    if (await fs.pathExists(packagePath)) {
      const pkg = await fs.readJson(packagePath);
      
      // 根据平台选择构建命令
      const platform = buildOptions.platform || 'h5';
      console.log('🔨 当前构建平台platform：', buildOptions);
      const platformCommands = {
        'h5': 'build:h5',
        'mp-weixin': 'build:mp-weixin',
        'mp-alipay': 'build:mp-alipay',
        'h5-scangzh': 'build:custom h5-scangzh',
        'h5-qywx': 'build:custom h5-qywx',
        'h5-alipaydd': 'build:custom h5-alipaydd',
        'h5-nonghang-zj': 'build:custom h5-nonghang-zj',
        'h5-nonghang-js': 'build:custom h5-nonghang-js',
        'h5-nonghang-js-old': 'build:custom h5-nonghang-js-old',
        'h5-huanzhe': 'build:custom h5-huanzhe',
        'weixin-huanzhe': 'build:custom weixin-huanzhe',
        'alipay-huanzhe': 'build:custom alipay-huanzhe'
      };
      
      const buildScript = platformCommands[platform] || 'build';
      
      if (pkg.scripts?.[buildScript]) {
        baseBuildCommand = `npm run ${buildScript}`;
      } else if (pkg.scripts?.build) {
        baseBuildCommand = `npm run build`;
      } else {
        // 如果没有build脚本，尝试检测构建工具
        baseBuildCommand = await detectBuildCommand(projectPath);
      }
    }
    
    // 添加API URL参数到构建命令
    if (buildOptions.apiUrl) {
      baseBuildCommand += ` --apiurl=${buildOptions.apiUrl}`;
    }
    
    // 获取针对Node版本优化的构建命令
    const buildCommand = nodeManager.getBuildCommand(nodeVersion, projectPath, baseBuildCommand);
    
    // 应用构建选项
    const buildEnv = {
      ...process.env,
      ...buildOptions.env
    };
    
    if (buildOptions.mode) {
      buildEnv.NODE_ENV = buildOptions.mode;
    }
    
    // 根据Node版本设置环境变量
    if (nodeVersion === 'node14') {
      buildEnv.NODE_OPTIONS = '--max-old-space-size=4096';
      buildEnv.SASS_BINARY_SITE = 'https://npmmirror.com/mirrors/node-sass'; // 解决node-sass下载问题
    } else if (nodeVersion === 'node22') {
      buildEnv.NODE_OPTIONS = '--no-deprecation';
    }
    
    const { stdout, stderr } = await execAsync(buildCommand, { 
      cwd: projectPath,
      timeout: 900000, // 15分钟超时
      env: buildEnv
    });
    
    // 检测输出目录
    const outputDir = await detectOutputDirectory(projectPath);
    
    console.log('✅ 项目构建完成');
    return { 
      stdout, 
      stderr, 
      outputDir,
      buildCommand,
      nodeVersion
    };

  } catch (error) {
    console.error('项目构建失败:', error);
    throw new Error(`项目构建失败: ${error.message}`);
  }
}

/**
 * 检测构建命令
 */
async function detectBuildCommand(projectPath) {
  // 检查各种构建工具配置文件
  const buildConfigs = [
    { file: 'webpack.config.js', command: 'npx webpack --mode=production' },
    { file: 'vite.config.js', command: 'npx vite build' },
    { file: 'vite.config.ts', command: 'npx vite build' },
    { file: 'rollup.config.js', command: 'npx rollup -c' },
    { file: '.parcelrc', command: 'npx parcel build src/index.html' }
  ];

  for (const config of buildConfigs) {
    if (await fs.pathExists(path.join(projectPath, config.file))) {
      return config.command;
    }
  }

  // 默认返回webpack构建命令
  return 'npx webpack --mode=production';
}

/**
 * 检测输出目录
 */
async function detectOutputDirectory(projectPath) {
  const possibleDirs = ['dist', 'build', 'out', 'public'];
  
  for (const dir of possibleDirs) {
    const dirPath = path.join(projectPath, dir);
    if (await fs.pathExists(dirPath)) {
      const stats = await fs.stat(dirPath);
      if (stats.isDirectory()) {
        return dir;
      }
    }
  }
  
  return 'dist'; // 默认目录
}

/**
 * 打包构建产物
 */
async function packageBuildOutput(projectId, projectPath, outputDir, platform = 'h5') {
  try {
    console.log('📦 开始打包构建产物...');
    
    const outputPath = path.join(projectPath, outputDir);
    if (!await fs.pathExists(outputPath)) {
      throw new Error(`构建输出目录不存在: ${outputDir}`);
    }

    const downloadsDir = path.join(__dirname, '../../downloads');
    await fs.ensureDir(downloadsDir);
    
    // 使用智能命名系统生成文件名
    const packageInfo = await packageIndexManager.generatePackageName(platform, projectId);
    const zipFileName = packageInfo.fileName;
    const zipFilePath = path.join(downloadsDir, zipFileName);
    
    await createZipArchive(outputPath, zipFilePath);
    
    const stats = await fs.stat(zipFilePath);
    const downloadUrl = `/downloads/${zipFileName}`;
    
    console.log('✅ 构建产物打包完成');
    
    return {
      fileName: zipFileName,
      filePath: zipFilePath,
      downloadUrl,
      fileSize: stats.size,
      createdAt: new Date().toISOString(),
      platform: packageInfo.platform,
      index: packageInfo.index,
      projectId: packageInfo.projectId
    };

  } catch (error) {
    console.error('打包失败:', error);
    throw new Error(`打包失败: ${error.message}`);
  }
}

/**
 * 创建ZIP压缩包
 */
function createZipArchive(sourceDir, outputPath) {
  return new Promise((resolve, reject) => {
    const output = fs.createWriteStream(outputPath);
    const archive = archiver('zip', { zlib: { level: 9 } });

    output.on('close', () => {
      console.log(`ZIP创建完成: ${archive.pointer()} bytes`);
      resolve();
    });

    archive.on('error', (err) => {
      reject(err);
    });

    archive.pipe(output);
    archive.directory(sourceDir, false);
    archive.finalize();
  });
}

/**
 * 清理历史构建产物，确保全新构建
 */
async function cleanPreviousBuild(projectPath, projectId) {
  try {
    logManager.sendLog(projectId, {
      level: 'info',
      message: '🧹 清理历史构建产物，确保全新构建'
    });

    // 常见的构建输出目录
    const buildDirs = [
      'dist',
      'build', 
      'unpackage',
      '.nuxt',
      '.next',
      'out',
      'public/build'
    ];

    // 常见的缓存目录
    const cacheDirs = [
      'node_modules/.cache',
      '.cache',
      '.parcel-cache',
      '.webpack',
      '.vite'
    ];

    // 常见的临时文件
    const tempFiles = [
      'build.log',
      'npm-debug.log',
      'yarn-debug.log',
      'yarn-error.log',
      '.env.local'
    ];

    let cleanedItems = 0;

    // 清理构建目录
    for (const dir of buildDirs) {
      const dirPath = path.join(projectPath, dir);
      if (await fs.pathExists(dirPath)) {
        await fs.remove(dirPath);
        cleanedItems++;
        console.log(`🗑️  已删除构建目录: ${dir}`);
      }
    }

    // 清理缓存目录
    for (const dir of cacheDirs) {
      const dirPath = path.join(projectPath, dir);
      if (await fs.pathExists(dirPath)) {
        await fs.remove(dirPath);
        cleanedItems++;
        console.log(`🗑️  已删除缓存目录: ${dir}`);
      }
    }

    // 清理临时文件
    for (const file of tempFiles) {
      const filePath = path.join(projectPath, file);
      if (await fs.pathExists(filePath)) {
        await fs.remove(filePath);
        cleanedItems++;
        console.log(`🗑️  已删除临时文件: ${file}`);
      }
    }

    logManager.sendLog(projectId, {
      level: 'info',
      message: `✨ 清理完成，共清理 ${cleanedItems} 个项目`,
      data: { cleanedItems }
    });

    console.log(`✅ 构建清理完成，共清理 ${cleanedItems} 个项目`);

  } catch (error) {
    console.error('清理历史构建失败:', error);
    logManager.sendLog(projectId, {
      level: 'warning',
      message: `⚠️ 清理历史构建时出现问题: ${error.message}`,
      data: { error: error.message }
    });
    // 不抛出错误，允许构建继续进行
  }
}

module.exports = router;
